import app from './app';
import { config } from './config';
import { MqttService } from './services/MqttService';
import { InfluxService } from './services/InfluxService';

class Server {
  private mqttService: MqttService;
  private influxService: InfluxService;

  constructor() {
    this.mqttService = new MqttService();
    this.influxService = new InfluxService();
  }

  async start(): Promise<void> {
    try {
      // // 初始化InfluxDB连接
      // await this.influxService.initialize();
      // console.log('✅ InfluxDB 连接已建立');

      // 初始化MQTT连接
      await this.mqttService.initialize();
      // TODO: 测试主动下发一条消息
      await this.mqttService.publish('testzqh/devices/1/commands', `Hello, MQTT! ${Date.now()}`);
      console.log('✅ MQTT 连接已建立');

      // 启动Express服务器
      app.listen(config.port, () => {
        console.log(`🚀 服务器运行在端口 ${config.port}`);
        console.log(`🌍 环境: ${config.nodeEnv}`);
        console.log(`📊 健康检查: http://localhost:${config.port}/health`);
      });

      // 优雅关闭处理
      this.setupGracefulShutdown();
    } catch (error) {
      console.error('❌ 服务器启动失败:', error);
      process.exit(1);
    }
  }

  private setupGracefulShutdown(): void {
    const shutdown = async (signal: string) => {
      console.log(`\n收到 ${signal} 信号，开始优雅关闭...`);
      
      try {
        await this.mqttService.disconnect();
        console.log('✅ MQTT 连接已关闭');
        
        // await this.influxService.close();
        // console.log('✅ InfluxDB 连接已关闭');
        
        console.log('✅ 服务器已优雅关闭');
        process.exit(0);
      } catch (error) {
        console.error('❌ 关闭过程中出错:', error);
        process.exit(1);
      }
    };

    process.on('SIGTERM', () => shutdown('SIGTERM'));
    process.on('SIGINT', () => shutdown('SIGINT'));
  }
}

// 启动服务器
const server = new Server();
server.start().catch((error) => {
  console.error('❌ 服务器启动失败:', error);
  process.exit(1);
});
